package com.cskaoyan.realm;

import com.cskaoyan.bean.CskaoyanmallAdmin;
import com.cskaoyan.service.AuthService;
import com.cskaoyan.service.PermissionService;
import com.cskaoyan.service.RoleService;
import com.cskaoyan.shiro.LoginToken;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;


import java.util.Arrays;
import java.util.Collections;
import java.util.Set;

/**
 * @author Fantasylkh
 */
@Component
public class AdminRealm extends AuthorizingRealm {

    @Autowired
    AuthService authService;

    @Autowired
    PermissionService permissionService;

    @Autowired
    RoleService roleService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        LoginToken token = (LoginToken) authenticationToken;

        String username = token.getUsername();

        CskaoyanmallAdmin admin = authService.selectAdminByName(username);

        if (!ObjectUtils.isEmpty(admin)) {

            return new SimpleAuthenticationInfo(admin.getUsername(), admin.getPassword(), this.getName());
        }
        return null;


    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) principalCollection.getPrimaryPrincipal();
        CskaoyanmallAdmin admin = authService.selectAdminByName(username);
        if (!ObjectUtils.isEmpty(admin)) {
            //数据库中获取用户权限
            Integer[] roleIds = admin.getRoleIds();

            Set<String> roleList = roleService.selectRolesByRoleIds(roleIds);

            Set<String> apiList = permissionService.selectPermissionsByRoleIds(roleIds);
            Set<String> permissionList = permissionService.selectPermissionsByApis(apiList);

            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            info.addRoles(roleList);
            info.addStringPermissions(permissionList);
            return info;
        }
        return null;
    }


}
